﻿using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Helper;
using MessageLib;
using MessageLib.Model;
using RabbitMQ.Client;
using RabbitMQ.Client.Events; 

namespace RabbitMQTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void LogEvent(string title, string data)
        {
            if (ckbShow.Checked)
            {
                //if (!(data is PublishMessage))
                {
                    if (txtInfo.InvokeRequired)
                    {
                        //后端线程向主线程记日志
                        Invoke(new Action<string, string>(LogEvent), title, data);
                    }
                    else
                    {
                        //主线程直接记日志

                        //if (ckbHex.Checked)
                        //{
                        //    txtInfo.Text += title + data.GetDataBytes().GetHexLog() + "\r\n";
                        //}
                        //else
                        {
                            // ReSharper disable once LocalizableElement
                            txtInfo.Text += title + data + Environment.NewLine;
                        }
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {

                //消费者
                ConnectionFactory factory = new ConnectionFactory
                {
                    //HostName = "127.0.0.1",
                    // HostName = "10.0.100.132",

                    HostName = "192.168.2.111",
                    UserName = "admin", //用户名
                    Password = "123456", //密码
                    Port = 5672,
                    AutomaticRecoveryEnabled = true
                };
                //设置端口后自动恢复连接属性即可
                //默认端口
                try
                {
                    using (IConnection conn = factory.CreateConnection())
                    {
                        using (IModel channel = conn.CreateModel())
                        {
                            //在MQ上定义一个持久化队列，如果名称相同不会重复创建 申请一个队列
                            channel.QueueDeclare("MyRabbitMQ2", true, false, false, null);

                            //输入1，那如果接收一个消息，但是没有应答，则客户端不会收到下一个消息
                            channel.BasicQos(0, 1, false);

                            LogEvent("消费者", "Listening...");

                            //在队列上定义一个消费者
                            QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);
                            //消费队列，并设置应答模式为程序主动应答
                            channel.BasicConsume("MyRabbitMQ2", false, consumer);

                            while (true)
                            {
                                //阻塞函数，获取队列中的消息
                                BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                                byte[] bytes = ea.Body;
                                string str = Encoding.UTF8.GetString(bytes);

                                LogEvent("消费者", "队列消息:" + str.ToString());
                                //回复确认
                                channel.BasicAck(ea.DeliveryTag, false);
                            }



                        }
                    }
                }
                catch (Exception ex)
                {

                    throw;
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                //ConnectionFactory factory = new ConnectionFactory
                //{
                //    HostName = "127.0.0.1",
                //    Port = 5672
                //};

                //消费者
                ConnectionFactory factory = new ConnectionFactory
                {
                    //HostName = "127.0.0.1",
                    // HostName = "10.0.100.132",

                    HostName = "192.168.2.111",
                    UserName = "admin", //用户名
                    Password = "123456", //密码
                    Port = 5672,
                    AutomaticRecoveryEnabled = true
                };

                //默认端口
                using (IConnection conn = factory.CreateConnection())
                {
                    using (IModel channel = conn.CreateModel())
                    {
                        //在MQ上定义一个持久化队列，如果名称相同不会重复创建
                        channel.QueueDeclare("MyRabbitMQ2", true, false, false, null);


                        while (true)
                        {
                            string message = string.Format("Message_{0}{1}", DateTime.Now, Console.ReadLine());
                            byte[] buffer = Encoding.UTF8.GetBytes(message);
                            IBasicProperties properties = channel.CreateBasicProperties();
                            properties.DeliveryMode = 2;
                            channel.BasicPublish("", "MyRabbitMQ2", properties, buffer);
                            LogEvent("生产", "消息发送成功：" + message);
                            Thread.Sleep(100);
                        }

                    }
                }
            });
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtInfo.Text = "";
        }

        readonly CommunManager _commun = new CommunManager(new MqttSerializeJson());
        private void button1_Click(object sender, EventArgs e)
        {
            _commun.Push(new AviProductionMessage(no_txt.Text, 1, 2, "sdf"));
            //Task.Run(() =>
            //{
            //    while (true)
            //    {
            //        _commun.Push(new AviProductionMessage(no_txt.Text, 1, 2, "sdf"));
            //        Thread.Sleep(100);
            //    }

            //});
        }

        private void button4_Click(object sender, EventArgs e)
        {
            _commun.Subscribe(new AviProductionMessage(no_txt.Text));
            _commun.AviMessageEvent += _commun_AviMessageEvent;
        }

        private void _commun_AviMessageEvent(AviProductionMessage obj)
        {
            LogEvent("接受", "队列消息:" + obj.TopicName);
        }
    }

    //public interface IProcessMessage
    //{
    //    void ProcessMsg(Message msg);
    //}

    //public class Message
    //{
    //    public string MessageID { get; set; }

    //    public string MessageTitle { get; set; }

    //    public string MessageBody { get; set; }

    //    public string MessageRouter { get; set; }
    //}
}
